module.exports = Behavior({
  properties: {
    minLength: {
      type: Number,
      value: 0,
    },

    required: Boolean,
  },
  data: {
    error: false,
  },

  observers: {
    'value,required,minLength': function (value, required, minLength) {
      const { raw } = this.data
      this.setData({ raw: false })

      if (!required || raw) return

      this.setData({ error: !value || value.length < minLength })
    },
  },

  lifetimes: {
    created() {
      this.setData({ raw: true })
    },
  },

  methods: {
    validate() {
      const { required, value, minLength } = this.data
      const isEmpty =
        !value ||
        String(value).length < minLength ||
        (typeof value === 'object' && Object.keys(value).length === 0) ||
        (Array.isArray(value) && value.length < minLength)

      let error = required && isEmpty
      if (this._validate) {
        error = error || !this._validate()
      }

      this.setData({ error })
      return !error
    },
  },
})
